﻿using Kaliko.ImageLibrary;
using Kaliko.ImageLibrary.Filters;
using Kaliko.ImageLibrary.Scaling;
using Karbel;
using Manina.Windows.Forms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Trimmer.Utility;

namespace Trimmer
{
    public partial class ListForm : Form
    {
        #region A Custom Renderer for Demonstrating the Control
        /// <summary>
        /// A renderer that displays useful information
        /// when the control is empty.
        /// </summary>
        private class DemoRenderer : ImageListView.ImageListViewRenderer
        {
            string[] infoTexts = new string[] { 
                "Start by adding some image files.",
                "You can switch between Thumbnails, Gallery, Pane and Details view modes.",
                "In Details mode, ImageListView displays image properties in columns.",
                "The appearance of ImageListView can be customized to a great extent.\r\nTry selecting a different renderer from the drop down.",
                "Size of generated thumbnails can be customized.\r\nImageListView will try to extract embedded Exif thumbnails if possible.",
            };

            int[] infoLocations = new int[]{
                23,
                190,
                244,
                360,
                490,
            };

            int current;
            //private Timer infoTimer;

            public DemoRenderer()
            {
                current = 0;
                //infoTimer = new Timer();
                //infoTimer.Interval = 5000;
                //infoTimer.Tick += new EventHandler(infoTimer_Tick);
                //infoTimer.Enabled = true;
            }

            //void infoTimer_Tick(object sender, EventArgs e)
            //{
            //    current++;
            //    if (current == infoTexts.Length)
            //        current = 0;

            //    ImageListView.Refresh();
            //}

            public override void Dispose()
            {
                //infoTimer.Dispose();
                base.Dispose();
            }

            /// <summary>
            /// Initializes the System.Drawing.Graphics used to draw
            /// control elements.
            /// </summary>
            /// <param name="g">The System.Drawing.Graphics to draw on.</param>
            public override void InitializeGraphics(Graphics g)
            {
                base.InitializeGraphics(g);
                g.SmoothingMode = SmoothingMode.HighQuality;
            }

            /// <summary>
            /// Draws an overlay image over the client area.
            /// </summary>
            /// <param name="g">The System.Drawing.Graphics to draw on.</param>
            /// <param name="bounds">The bounding rectangle of the client area.</param>
            public override void DrawOverlay(Graphics g, Rectangle bounds)
            {
                //if (ImageListView.Items.Count != 0)
                //{
                //    infoTimer.Enabled = false;
                //    return;
                //}

                //if (!infoTimer.Enabled)
                //{
                //    current = 0;
                //    infoTimer.Enabled = true;
                //}

                //DrawToolTip(g, infoLocations[current], infoTexts[current]);
            }

            /// <summary>
            /// Draws a tooltip.
            /// </summary>
            private void DrawToolTip(Graphics g, int x, string s)
            {
                bool onLeft = (x < ImageListView.ClientRectangle.Width / 2);
                int width = 200;
                Size sz = Size.Round(g.MeasureString(s, ImageListView.Font, width));
                sz.Width += 20;
                sz.Height += 10;
                int y = 12;

                int arrowOffset = 15;
                if (!onLeft) arrowOffset = sz.Width - 30;
                if (!onLeft) x -= sz.Width - 45;

                int fillet = 10;
                if (fillet > sz.Height / 2) fillet = sz.Height / 2;
                int shadow = 3;

                using (GraphicsPath path = new GraphicsPath())
                {
                    path.AddLine(x - 20 + arrowOffset, y, x - 15 + arrowOffset, y - 10);
                    path.AddLine(x - 15 + arrowOffset, y - 10, x - 10 + arrowOffset, y);
                    path.AddLine(x - 10 + arrowOffset, y, x + sz.Width - 20 - fillet, y);
                    path.AddArc(x + sz.Width - 20 - 2 * fillet, y, 2 * fillet, 2 * fillet, 270.0f, 90.0f);
                    path.AddLine(x + sz.Width - 20, y + fillet, x + sz.Width - 20, y + sz.Height - fillet);
                    path.AddArc(x + sz.Width - 20 - 2 * fillet, y + sz.Height - 2 * fillet, 2 * fillet, 2 * fillet, 0.0f, 90.0f);
                    path.AddLine(x + sz.Width - 20 - fillet, y + sz.Height, x - 20 + fillet, y + sz.Height);
                    path.AddArc(x - 20, y + sz.Height - 2 * fillet, 2 * fillet, 2 * fillet, 90.0f, 90.0f);
                    path.AddLine(x - 20, y + sz.Height - fillet, x - 20, y + fillet);
                    path.AddArc(x - 20, y, 2 * fillet, 2 * fillet, 180.0f, 90.0f);
                    path.AddLine(x - 20 + fillet, y, x - 20 + arrowOffset, y);
                    path.CloseFigure();

                    path.Transform(new Matrix(1, 0, 0, 1, shadow, shadow));
                    using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Gray)))
                    {
                        g.FillPath(b, path);
                    }
                    path.Transform(new Matrix(1, 0, 0, 1, -shadow, -shadow));

                    using (Brush b = new LinearGradientBrush(path.GetBounds(), Color.BlanchedAlmond, Color.White, LinearGradientMode.ForwardDiagonal))
                    {
                        g.FillPath(b, path);
                    }
                    using (Pen p = new Pen(SystemColors.InfoText))
                    {
                        g.DrawPath(p, path);
                    }
                    using (Brush b = new SolidBrush(SystemColors.InfoText))
                    {
                        g.DrawString(infoTexts[current], ImageListView.Font, b, new Rectangle(x - 20 + 10, y + 5, sz.Width - 16, sz.Height - 10));
                    }
                }
            }
        }
        #endregion

        #region Constructor
        public ListForm()
        {
            InitializeComponent();

            Application.Idle += new EventHandler(Application_Idle);

            // Populate renderer dropdown
            Assembly assembly = Assembly.GetAssembly(typeof(ImageListView));
            int i = 0;
            foreach (Type t in assembly.GetTypes())
            {
                if (t.BaseType == typeof(Manina.Windows.Forms.ImageListView.ImageListViewRenderer))
                {
                    renderertoolStripComboBox.Items.Add(new RendererItem(t));
                    if (t.Name == "DefaultRenderer")
                        renderertoolStripComboBox.SelectedIndex = i;
                    i++;
                }
            }
            imageListView1.SetRenderer(new DemoRenderer());



            //imageListView1.Items.AddRange(Directory.GetFiles(folder, "*.JPG"));

        }

        private void ListForm_Load_1(object sender, EventArgs e)
        {
            this.Visible = false;

            using (Login login = new Login())
            {
                DialogResult dr = login.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    this.Visible = true;

                    AppSession appSession = new AppSession();
                    AppSession.DataManager = new DataManager(login.ConnectionString);
                }
                else
                    Application.Exit();
            }

            btnCrop.Click += btnCrop_Click;
            imageListView1.ItemClick += imageListView1_ItemClick;
            cmbKat.SelectedIndexChanged += cmbKat_SelectedIndexChanged;
            cmbSeri.SelectedIndexChanged += cmbSeri_SelectedIndexChanged;
            x120ToolStripMenuItem.PerformClick();
            GetStatus();
        }




        void cmbSeri_SelectedIndexChanged(object sender, EventArgs e)
        {
            selKategori = string.Empty;
            selSeri = cmbSeri.SelectedItem.ToString();
            List();
        }

        void cmbKat_SelectedIndexChanged(object sender, EventArgs e)
        {
            selKategori = cmbKat.SelectedItem.ToString();
            selSeri = string.Empty;
            List();
        }
        #endregion

        string id = string.Empty;
        string targetDirectory = @"D:\AksPhoto";
        string targetDirectoryR = @"D:\AksPhoto.rect";
        string newDirectory = @"D:\AksPhoto.Cropped1";
        //string hueDirectory = @"D:\AksPhoto.hue";


        #region Refresh UI Cues
        void Application_Idle(object sender, EventArgs e)
        {
            // Refresh UI cues
            removeToolStripButton.Enabled = (imageListView1.SelectedItems.Count > 0);
            removeToolStripButton.Enabled = (imageListView1.SelectedItems.Count > 0);
            removeAllToolStripButton.Enabled = (imageListView1.Items.Count > 0);

            thumbnailsToolStripButton.Checked = (imageListView1.View == Manina.Windows.Forms.View.Thumbnails);
            detailsToolStripButton.Checked = (imageListView1.View == Manina.Windows.Forms.View.Details);
            galleryToolStripButton.Checked = (imageListView1.View == Manina.Windows.Forms.View.Gallery);
            paneToolStripButton.Checked = (imageListView1.View == Manina.Windows.Forms.View.Pane);

            clearCacheToolStripButton.Enabled = (imageListView1.Items.Count > 0);

            deleteToolStripMenuItem.Enabled = (imageListView1.SelectedItems.Count > 0);

            x48ToolStripMenuItem.Checked = (imageListView1.ThumbnailSize == new Size(48, 48));
            x96ToolStripMenuItem.Checked = (imageListView1.ThumbnailSize == new Size(96, 96));
            x120ToolStripMenuItem.Checked = (imageListView1.ThumbnailSize == new Size(120, 120));
            x150ToolStripMenuItem.Checked = (imageListView1.ThumbnailSize == new Size(150, 150));
            x200ToolStripMenuItem.Checked = (imageListView1.ThumbnailSize == new Size(200, 200));

            rotateCCWToolStripButton.Enabled = (imageListView1.SelectedItems.Count > 0);
            rotateCWToolStripButton.Enabled = (imageListView1.SelectedItems.Count > 0);
        }
        #endregion

        #region Add/Remove Items
        string folder = @"D:\AksPhoto.Cropped";
        private void addToolStripButton_Click(object sender, EventArgs e)
        {
            //string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\CEAks";
            //if (!Directory.Exists(folder))
            //    Directory.CreateDirectory(folder);


            if (Directory.Exists(folder))
                openFileDialog.InitialDirectory = folder;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                folder = Path.GetDirectoryName(openFileDialog.FileName);
                imageListView1.Items.AddRange(openFileDialog.FileNames);
            }
        }

        private void removeToolStripButton_Click(object sender, EventArgs e)
        {
            // Suspend the layout logic while we are removing items.
            // Otherwise the control will be refreshed after each item
            // is removed.
            imageListView1.SuspendLayout();

            // Remove selected items
            foreach (var item in imageListView1.SelectedItems)
                imageListView1.Items.Remove(item);

            // Resume layout logic.
            imageListView1.ResumeLayout(true);
        }

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            removeToolStripButton_Click(sender, e);
        }

        private void removeAllToolStripButton_Click(object sender, EventArgs e)
        {
            imageListView1.Items.Clear();
        }
        #endregion

        #region Switch Renderers
        private struct RendererItem
        {
            public Type Type;

            public override string ToString()
            {
                return Type.Name;
            }

            public RendererItem(Type type)
            {
                Type = type;
            }
        }

        private void renderertoolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Change the renderer
            Assembly assembly = Assembly.GetAssembly(typeof(ImageListView));
            RendererItem item = (RendererItem)renderertoolStripComboBox.SelectedItem;
            ImageListView.ImageListViewRenderer renderer = assembly.CreateInstance(item.Type.FullName) as ImageListView.ImageListViewRenderer;
            imageListView1.SetRenderer(renderer);
            imageListView1.Focus();
        }
        #endregion

        #region Switch View Modes
        private void detailsToolStripButton_Click(object sender, EventArgs e)
        {
            imageListView1.View = Manina.Windows.Forms.View.Details;
        }

        private void thumbnailsToolStripButton_Click(object sender, EventArgs e)
        {
            imageListView1.View = Manina.Windows.Forms.View.Thumbnails;
        }

        private void galleryToolStripButton_Click(object sender, EventArgs e)
        {
            imageListView1.View = Manina.Windows.Forms.View.Gallery;
        }

        private void paneToolStripButton_Click(object sender, EventArgs e)
        {
            imageListView1.View = Manina.Windows.Forms.View.Pane;
        }
        #endregion

        #region Update Status Bar
        private void imageListView1_ThumbnailCached(object sender, ThumbnailCachedEventArgs e)
        {
            // This event is fired after a new thumbnail is cached.
            UpdateStatus(string.Format("Cached image: {0}", e.Item.Text));
            timerStatus.Enabled = true;
        }

        private void imageListView1_SelectionChanged(object sender, EventArgs e)
        {
            UpdateStatus();
        }

        private void timerStatus_Tick(object sender, EventArgs e)
        {
            UpdateStatus();
            timerStatus.Enabled = false;
        }

        private void UpdateStatus(string text)
        {
            toolStripStatusLabel.Text = text;
        }

        private void UpdateStatus()
        {
            if (imageListView1.Items.Count == 0)
                UpdateStatus("Ready");
            else if (imageListView1.SelectedItems.Count == 0)
                UpdateStatus(string.Format("{0} images", imageListView1.Items.Count));
            else
                UpdateStatus(string.Format("{0} images ({1} selected)", imageListView1.Items.Count, imageListView1.SelectedItems.Count));
        }
        #endregion

        #region Modify Column Headers
        private void columnsToolStripButton_Click(object sender, EventArgs e)
        {
            //ChooseColumns form = new ChooseColumns();
            //form.imageListView = imageListView1;
            //form.ShowDialog();
        }
        #endregion

        #region Change Thumbnail Size
        private void x48ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            imageListView1.ThumbnailSize = new Size(48, 48);
        }

        private void x96ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            imageListView1.ThumbnailSize = new Size(96, 96);
        }

        private void x120ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            imageListView1.ThumbnailSize = new Size(120, 120);
        }

        private void x150ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            imageListView1.ThumbnailSize = new Size(150, 150);
        }

        private void x200ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            imageListView1.ThumbnailSize = new Size(200, 200);
        }

        private void clearCacheToolStripButton_Click(object sender, EventArgs e)
        {
            imageListView1.ClearThumbnailCache();
        }
        #endregion

        #region Rotate Selected Images
        private void rotateCCWToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Rotating will overwrite original images. Are you sure you want to continue?",
                "ImageListViewDemo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                foreach (ImageListViewItem item in imageListView1.SelectedItems)
                {
                    item.BeginEdit();
                    using (Image img = Image.FromFile(item.FileName))
                    {
                        img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        img.Save(item.FileName);
                    }
                    item.Update();
                    item.EndEdit();
                }
            }
        }

        private void rotateCWToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Rotating will overwrite original images. Are you sure you want to continue?",
                "ImageListViewDemo", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                foreach (ImageListViewItem item in imageListView1.SelectedItems)
                {
                    item.BeginEdit();
                    using (Image img = Image.FromFile(item.FileName))
                    {
                        img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        img.Save(item.FileName);
                    }
                    item.Update();
                    item.EndEdit();
                }
            }
        }
        #endregion




        string selSeri = string.Empty;
        string selKategori = string.Empty;
        List<string> Kat = new List<string>();
        List<string> Seri = new List<string>();
        Dictionary<string, A> Sira = new Dictionary<string, A>();

        Dictionary<string, Rectangle> listR = new Dictionary<string, Rectangle>();
        List<string> listF = new List<string>();

        string GetFN(string fileName)
        {
            return System.IO.Path.GetFileNameWithoutExtension(fileName);
        }

        void GetStatus()
        {
            foreach (string fileName in Directory.GetFiles(targetDirectory))
                listF.Add(GetFN(fileName));
            listF.Sort();

            DataTable dt = AppSession.DataManager.ExecuteDataTable("GetAksSira");
            foreach (DataRow r in dt.Rows)
            {
                string S = r["Sira"].ToString();
                string Ktg = r["Kategori"].ToString();
                string Se = r["AksSeriId"].ToString();
                string Nm = r["StokKod"].ToString();
                int Id = (int)r["AksesuarId"];

                if (!Kat.Contains(Ktg))
                    Kat.Add(Ktg);

                A oA = new A();
                oA.AksesuarId = Id;
                oA.AksSeriId = Se;
                oA.Kategori = Ktg;
                oA.StokKod = Nm;

                if (!Sira.ContainsKey(S))
                    Sira.Add(S, oA);

                if (Se != "0")
                    if (!Seri.Contains(Se))
                        Seri.Add(Se);
            }

            Kat.Sort();
            Seri.Sort();

            cmbKat.Items.AddRange(Kat.ToArray());
            cmbSeri.Items.AddRange(Seri.ToArray());
        }


        void List()
        {
            //Before clearing items call:
            //imageListView1.SuspendLayout();

            imageListView1.Items.Clear();
            List<string> files = new List<string>();
            for (int i = 0; i < listF.Count; i++)
            {
                //FileInfo fi = new FileInfo(fileName);
                //using (Image objImage = Image.FromFile(newDirectory + "\\" + listF[i] + ".JPG"))

                string Sr = listF[i];
                if (Sira.ContainsKey(Sr))
                    if (Sira[Sr].Kategori == selKategori ||
                    Sira[Sr].AksSeriId == selSeri)
                    {
                        files.Add(newDirectory + "\\" + Sr + ".JPG");

                        //FileStream fs = new FileStream(newDirectory + "\\" + Sr + ".JPG", FileMode.Open, FileAccess.Read);
                        //Image objImage = System.Drawing.Image.FromStream(fs);
                        //group1.Items.Add(new GalleryItem(objImage, Sr, Sira[Sr].AksesuarId.ToString()));

                        //PictureEdit picture = new DevExpress.XtraEditors.PictureEdit();
                        //picture.Width = objImage.Width;
                        //picture.Height = objImage.Height;
                        //picture.Image = objImage;
                        //picture.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
                        //picture.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;

                        //new ToolTip().SetToolTip(picture, Sira[Sr].AksesuarId.ToString());
                        //flowLayoutPanel1.Controls.Add(picture);

                        //fs.Close();
                        //fs.Dispose();
                    }
            }
            //Directory.GetFiles(folder, "*.JPG")
            imageListView1.Items.AddRange(files.ToArray());

            //when you are done adding items call:
            //imageListView1.ResumeLayout();

        }

        void imageListView1_ItemClick(object sender, ItemClickEventArgs e)
        {
            string Sr = Path.GetFileNameWithoutExtension(e.Item.FileName);
            using (DetailA da = new DetailA(e.Item.FileName, Sira[Sr].StokKod))
                da.ShowDialog();
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }

        void btnCrop_Click(object sender, EventArgs e)
        {            
            Bitmap bm;
            byte[] Photo1, Photo2;
            
            foreach (string fileName in Directory.GetFiles(targetDirectoryR))
                using (StreamReader reader = new StreamReader(fileName))
                {
                    string[] r = reader.ReadLine().Split(",".ToCharArray());
                    string id = GetFN(fileName);

                    listR.Add(id, new Rectangle(int.Parse(r[0]), int.Parse(r[1]), int.Parse(r[2]), int.Parse(r[3])));
                }


            for (int i = 0; i < listF.Count; i++)
            {
                string idx = listF[i];
                {
                    FileStream fs = new FileStream(targetDirectory + "\\" + listF[i] + ".JPG", FileMode.Open, FileAccess.Read);
                    //using (Image img = Image.FromFile(targetDirectory + "\\" + idx + ".JPG"))
                    using (Image objImage = System.Drawing.Image.FromStream(fs))
                    {
                        Rectangle cR = listR[idx];

                        bm = new Bitmap(objImage);
                        Photo1 = ApplyAll(bm, cR, 32);
                        bm = new Bitmap(objImage);
                        Photo2 = ApplyAll(bm, cR, 2);
                        StoreBlob2DataBase(-int.Parse(listF[i]), Photo1, Photo2);

                        fs.Close();
                        fs.Dispose();
                    }
                    //float hue;
                    //using (FileStream s = new FileStream(newDirectory + "\\" + idx + ".JPG", FileMode.Open))
                    //{
                    //    Bitmap img = (Bitmap)Image.FromStream(s);
                    //    if (img != null)
                    //    {
                    //        hue = GetDominantColor(img).GetHue();
                    //        using (StreamWriter writer = new StreamWriter(hueDirectory + "\\" + idx + ".txt", true))
                    //        {
                    //            writer.WriteLine(hue);
                    //        }
                    //    }
                    //}
                }
            }
            MessageBox.Show("Done.");
        }



        public Color GetDominantColor(Bitmap image)
        {
            if (image != null)
            {
                BitmapData bitmapData1 = image.LockBits(new Rectangle(0, 0,
                                         image.Width, image.Height),
                                         ImageLockMode.ReadOnly,
                                         PixelFormat.Format32bppArgb);

                int a = 0, r = 0, g = 0, b = 0;
                unsafe
                {
                    byte* imagePointer1 = (byte*)bitmapData1.Scan0;
                    for (int i = 0; i < bitmapData1.Height; i++)
                    {
                        for (int j = 0; j < bitmapData1.Width; j++)
                        {
                            a++;
                            b += imagePointer1[0];
                            g += imagePointer1[1];
                            r += imagePointer1[2];
                            imagePointer1 += 4;
                        }

                        //4 bytes per pixel
                        imagePointer1 += bitmapData1.Stride - (bitmapData1.Width * 4);
                    }

                }

                image.UnlockBits(bitmapData1);

                return Color.FromArgb(r / a, g / a, b / a);
            }
            return Color.Transparent;
        }

        private byte[] ApplyAll(Bitmap b, Rectangle cR, int katsayi)
        {
            using (Image objImage = (Image)b)
            {
                cR.Inflate(3, 3);   //3'er pixel genişlet her yönde!

                KalikoImage sharpimg = new KalikoImage(Crop(objImage, cR));
                if (katsayi == 32)
                    sharpimg = sharpimg.Scale(new FitScaling(32, 32));
                else
                    sharpimg.Resize(sharpimg.Width / 2, sharpimg.Height / 2);
                sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2F, 0.5F, 20));   //threshold: http://www.damiensymonds.com.au/tut_usm.html
                using (MemoryStream mstr = new MemoryStream())
                {
                    sharpimg.SaveJpg(mstr, 90);
                    sharpimg.Dispose();
                    return mstr.ToArray();
                }
            }
        }


        public Image Crop(Image bmp, Rectangle cropRect)
        {
            Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);
            using (Graphics g = Graphics.FromImage(target))
            {
                g.DrawImage(bmp, new Rectangle(0, 0, target.Width, target.Height),
                                 cropRect,
                                 GraphicsUnit.Pixel);
            }
            return (Image)target;
        }


        protected static void StoreBlob2DataBase(int AksesuarId, byte[] content1, byte[] content2)
        {
            SqlConnection con = new SqlConnection(AppSession.DataManager.ConnectionString);
            con.Open();
            try
            {
                SqlCommand insert = new SqlCommand("UpdAksPhoto2", con);
                insert.CommandType = CommandType.StoredProcedure;
                //"insert into AksesuarPhotos (AksesuarId, Photo1, Photo2) values (@id, @image1, @image2)", con);
                //"update AksesuarPhotos set Photo2 = @image where AksesuarId = @id", con);
                //"update AksesuarPhotos set Photo1 = @image where AksesuarId = @id", con);
                SqlParameter idParameter = insert.Parameters.Add("@AksesuarId", SqlDbType.Int);
                idParameter.Value = AksesuarId;
                //imageParameter.Size = content.Length;
                SqlParameter imageParameter1 = insert.Parameters.Add("@Photo1", SqlDbType.Binary);
                imageParameter1.Value = content1;
                imageParameter1.Size = content1.Length;
                SqlParameter imageParameter2 = insert.Parameters.Add("@Photo2", SqlDbType.Binary);
                imageParameter2.Value = content2;
                imageParameter2.Size = content2.Length;
                insert.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }

    }
}
